<template>
  <div class="app-container">
    <el-card id="dlls_card" class="box-card" style="text-align: center;">
      <div>
        <drag-head
          ref="dragHeadRef"
          :show-all-filter-condition="showAllFilterCondition"
          :store-names="storeName"
          :head-columns="tableHead"
          :data="projectList"
          :loading="loading"
          @handleCommand="handleCommand"
          @openComment="openComment"
          @openComments="openComments"
          @handleSelectionChange="handleSelectionChange"
          @sort_change="sort_change"
          @fresh="fresh"
        >
          <!-- :data="[1]" projectList-->
        </drag-head>
        <div class="" style="margin-top: 10px; float: right;margin-bottom: 10px;">
          <el-pagination
            :page-sizes="[10, 15, 20, 25, 50]"
            :current-page.sync="page"
            :page-size="page_size"
            layout="sizes, prev, pager, next, total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    <!-- 开启自动回复-->
    <el-dialog
      title="自动评论回复"
      :visible.sync="moreDialog.visibleReply"
      width="1000px"
      append-to-body
    >
      <el-form
        :model="moreDialog"
        ref="ruleForm"
        label-width="130px"
      >
        <el-form-item label="选择回复模板ID" required="">
          <el-select v-model="moreDialog.reply_template_id">
            <el-option
              v-for="item in moreDialog.replayTemplateList"
              :key="item.ID"
              :value="item.ID"
              :label="item.ID+(item.note?`(${item.note})`:'')"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="saveReply"
          >确认保存</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getProjectList,
  openCommentControls,
  closeCommentControls,
  CommentsAutoReplyOpen,
  CommentsAutoReplyClose,
  getReplyList
} from '../../api'

import DragHead from './dragHead.vue'
import NoticeBar from './noticeBar.vue'
import JsonExcel from 'vue-json-excel'
export default {
  // eslint-disable-next-line vue/no-unused-components
  components: { DragHead, DownloadExcel: JsonExcel, NoticeBar },
  data() {
    return {
      moreDialog:{
        visibleReply:false,
        reply_template_id: "",
        replayTemplateList:[],
        id:""
      },
      storeName: 'advertisingList',
      pickerOptions: {
        // 今天 昨天 最近三天 最近七天 本月 上个月
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick: (picker) => {
              const start = new Date()
              start.setTime(start.getTime() - 24 * 60 * 60 * 1000)
              start.setHours(0, 0, 0, 0)
              const end = new Date(start.getTime() + 24 * 60 * 60 * 1000 - 1)
              end.setHours(23, 59, 59, 999)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近七天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '本月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setDate(1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '上个月',
            onClick: (picker) => {
              const start = new Date()
              start.setMonth(start.getMonth() - 1, 1)
              start.setHours(0, 0, 0, 0)
              const end = new Date(
                start.getFullYear(),
                start.getMonth() + 1,
                0
              )
              end.setHours(23, 59, 59, 999)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      showAllFilterCondition: false,
      tableHead: [
        {
          label: '户ID',
          prop: 'advertiser_id',
          width: 100,
          sortable: false,
          show: true
        },
        {
          label: '户名称',
          prop: 'advertiser_name',
          width: 200,
          sortable: false,
          show: true
        },
        {
          label: '广告ID',
          prop: 'promotion_id',
          width: 100,
          sortable: false,
          show: true
        },
        {
          label: '广告名称',
          prop: 'name',
          width: 200,
          sortable: false,
          show: true
        },
        {
          label: '操作',
          prop: 'operas',
          width: 300,
          sortable: false,
          show: true
        },
        {
          label: '状态',
          prop: 'status',
          width: 100,
          sortable: false,
          show: true
        },
        {
          label: '更新时间',
          prop: 'update_time',
          width: 100,
          sortable: false,
          show: true
        },
        {
          label: '是否控评',
          prop: 'is_comment_control',
          width: 200,
          sortable: false,
          show: true
        },
        {
          label: '是否开启自动回评',
          prop: 'is_comment_auto_reply_open',
          width: 200,
          sortable: false,
          show: true
        },
        {
          label: '开启回评的ID',
          prop: 'comment_auto_reply_open_id',
          width: 200,
          sortable: false,
          show: true
        },
        {
          label: '回复模板ID',
          prop: 'reply_template_id',
          width: 200,
          sortable: false,
          show: true
        },
        {
          label: '备注',
          prop: 'note',
          width: 200,
          sortable: false,
          show: true
        }

      ],
      page_size: 50,
      page: 1,
      total: 0,
      projectList: [],
      seletctedAdUserPromotionId: [],
      loading: false,
      value1: ['', '']
    }
  },
  watch: {},
  mounted() {

  },
  created() {
    var url = window.location.href
    this.$nextTick(() => {
      let arr = localStorage.getItem(this.storeName)
      if (arr != null && arr.length != this.tableHead.length) {
        localStorage.removeItem(this.storeName)
        arr = localStorage.setItem(this.storeName, JSON.stringify(this.tableHead))
      }
      if (arr) {
        const isClearLocal = JSON.parse(arr).find(
          (item) =>
            item.prop === 'advertiser_name' && (!item.show || item.show === false)
        )
        if (isClearLocal) {
          const newArr = []
          JSON.parse(arr).forEach((item) => {
            if (item !== null) {
              if (!item['show']) {
                item['show'] = true
              }
              newArr.push(item)
            }
          })
          localStorage.setItem(this.storeName, JSON.stringify(newArr))
        }
      } else {
        localStorage.setItem(this.storeName, JSON.stringify(this.tableHead))
      }
    })
    var role = Number(window.localStorage.getItem('role'))

    const date = new Date()
    const year = date.getFullYear() // 获取完整的年份(4位)
    let month = date.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
    let strDate = date.getDate() // 获取当前日(1-31)
    if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
    if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
    this.value1 = [
      `${year}-${month}-${strDate}`,
      `${year}-${month}-${strDate}`
    ]
    this.getList()
  },
  methods: {
    async getSonList() {
      const res = await getSonList({}).catch((e) => e)
      if (res.code === 0) {
        this.sonList = res.data.list
      } else {
        this.$message.error(res.msg)
      }
    },

    openCustomModal() {
      this.$refs.dragHeadRef.openCustomModal()
    },
    fresh() {
      this.projectList = []
      this.getList()
    },
    async getList() {
      const {
        page_size,
        page
      } = this

      this.loading = true
      const res = await getProjectList({
        page_size,
        page
      }).catch((e) => e)
      this.loading = false
      this.$refs.dragHeadRef.renderTable()

      // console.log('getProjectList', res)
      if (res.code === 0) {
        this.seletctedAdUserPromotionId = []
        this.total = Number(res.data.total)
        this.projectList = res.data.list
      } else {
        this.projectList = []
        this.loading = false
        this.$message.error(res.msg)
      }
    },
    handleCommand(command) {
      // console.log('command.val', command.val)
      const id = command.val.id
      const replyStatus = command.val.is_comment_auto_reply_open

      switch (command.key) {
        case 'cost': // 计划小时报表
          // this.openHourPlanListDialog(id);
          break
      }
    },
    async openComment(...args) {
      // console.log('argsargsargs', args[0].is_comment_control)
      if (args[0].is_comment_control) {
        const res = await closeCommentControls({
          ad_promotion_merchant_relation_id: args[0].id
        }).catch((e) => e)
        if (res.code === 0) {
          this.$message.success('关闭成功');

          [args[0].id].map((id) => {
            this.projectList.map((item) => {
              if (id === item.id) {
                item.is_comment_control = false
              }
            })
          })
        } else {
          this.$message.error(res.msg)
        }
      } else {
        const res = await openCommentControls({
          ad_promotion_merchant_relation_id: args[0].id,
          reply_template_id:args[0].reply_template_id
        }).catch((e) => e)

        if (res.code === 0) {
          this.$message.success('开启成功');

          // 修改表格单行状态 不刷新列表
          [args[0].id].map((id) => {
            this.projectList.map((item) => {
              if (id === item.id) {
                item.is_comment_control = true
              }
            })
          })
        } else {
          this.$message.error(res.msg)
        }
      }
    },
    async getReplyList() {
      let res = await getReplyList({
        page_size: 50,
        page: 1,
      }).catch((e) => e);
      if (res.code === 0) {
        console.log("getReplyList====", res.data);
        this.moreDialog.replayTemplateList = res.data;
        this.moreDialog.reply_template_id = res.data[0].ID;
      } else {
        this.$message.error(res.msg);
      }
    },
    async saveReply() {
      const res = await CommentsAutoReplyOpen({
        ad_promotion_merchant_relation_ids: [Number(this.moreDialog.id)],
        reply_template_id:this.moreDialog.reply_template_id
      }).catch((e) => e)

      if (res.code === 0) {
        this.$message.success('开启成功');

        // 修改表格单行状态 不刷新列表
        [args[0].id].map((id) => {
          this.projectList.map((item) => {
            if (id === item.id) {
              item.is_comment_auto_reply_open = true
            }
          })
        })
      } else {
        this.$message.error(res.msg)
      }
    },
    async openComments(...args) {
      // console.log('argsargsargs', args[0].is_comment_control)
      if (args[0].is_comment_auto_reply_open) {
        const res = await CommentsAutoReplyClose({
          ad_promotion_merchant_relation_id: [Number(args[0].id)]
        }).catch((e) => e)
        if (res.code === 0) {
          this.$message.success('关闭成功');

          [args[0].id].map((id) => {
            this.projectList.map((item) => {
              if (id === item.id) {
                item.is_comment_auto_reply_open = false
              }
            })
          })
        } else {
          this.$message.error(res.msg)
        }
      } else {
        this.moreDialog.visibleReply = true;
        this.moreDialog.id=args[0].id;
        this.getReplyList();
      }
    },
    sort_change(column) {
    },
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.seletctedAdUserPromotionId = val.map((item) => item.id)
      } else {
        this.seletctedAdUserPromotionId = []
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val

      this.getList()
    }
  }
}
</script>

<style lang="scss">
  html,
  body {
    height: 100%;
  }

  .scroll::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 10px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 12px;
  }

  .scroll::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 8px;
    -webkit-box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.2);
    background: #fff;
  }

  .scroll::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.8);
    border-radius: 10px;
    background: #888;
  }

  .dataPicker {
    white-space: pre;
    margin: 0 10px 0 30px;
  }
  .inputM {
    margin: 0 5px;
    width: 150px;
  }
  .operBtn {
    text-align: center;
  }
  .export-btn {
    display: inline;
    margin-left: 10px;
  }
  .pddTable {
    .el-table .cell {
      // white-space: nowrap;
      // overflow: hidden;
      // text-overflow: ellipsis;
    }
  }

  .totalTitle {
    font-weight: 700;
    font-size: 14px;
  }

  .dialog-box-distinguish {
    position: relative;
  }
  .dynamicWordBagItem {
    cursor: pointer;
    color: #409eff;
  }

  .el-range-editor--small .el-range-separator {
    margin: 0 10px !important;
  }
</style>
